//
//  SubjectsManager.m
//  
//
//  Created by Christian Speich on 17.12.07.
//  Copyright 2007 Christian Speich. All rights reserved.
//

#import "SubjectsManager.h"
#import "Subject.h"


@implementation SubjectsManager

- (id) init
{
	self = [super init];
	if (self != nil) {
#ifdef IPHONE
		file = @"/var/root/Library/iMarks/test.xml";
#else
		file = @"/Users/christian/noten_backup.xml";
#endif
		xmlClass = [[XMLClass alloc] init];
		[self readFile];
		
		[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_updateStatus:) name:@"MarkHasChanged" object:nil];
	}
	return self;
}


+ (id)sharedInstance
{
	static id shared = nil;
	if (shared == nil) {
		shared = [[SubjectsManager alloc] init];
	}
	return shared;
}

- (void)setFile:(NSString*)_file
{
	file = _file;
}

- (NSString*)file
{
	return file;
}

- (bool)readFile
{
	if (pupil)
		[pupil release];
	[xmlClass parseXMLFile:file];
	pupil = [xmlClass pupil];
	
	return YES;
}

- (bool)writeFile
{
	NSURL *xmlURL = [NSURL fileURLWithPath:file];
	NSMutableString* xml = [[NSMutableString alloc] initWithCapacity:50];
	
	[xml appendString:@"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"];
	[xml appendString:[pupil xml]];
	[xml writeToURL:xmlURL atomically:YES encoding:NSUTF8StringEncoding error:NULL];

    return YES;
}

- (NSMutableArray*)mainSubjects
{	
	NSMutableArray* mainSubjects= [[NSMutableArray alloc] initWithCapacity:1];
	
	int i, count = [[pupil subjects] count];
	for (i = 0; i < count; i++) {
		Subject* obj = [[pupil subjects] objectAtIndex:i];
		if ([[obj type] isEqualToString:@"main"]) {
			[mainSubjects addObject:obj];
		}
	}
	
	return mainSubjects;
}

- (NSMutableArray*)subjects
{
	NSMutableArray* subjects= [[NSMutableArray alloc] initWithCapacity:1];
	
	int i, count = [[pupil subjects] count];
	for (i = 0; i < count; i++) {
		Subject* obj = [[pupil subjects] objectAtIndex:i];
		if ([[obj type] isEqualToString:@"other"]) {
			[subjects addObject:obj];
		}
	}
	
	return subjects;
}

- (Subject*)subjectAtIndex:(int)i
{
	if (i < [[pupil subjects] count]) {
		return [[pupil subjects] objectAtIndex:i];
	}
	return nil;
}

- (float)average
{
	float average = 0.0f;
	int y = 0;
	int i;
	int count;
	
	count = [[pupil subjects] count];
	for (i = 0; i < count; i++) {
		Subject * obj = [[pupil subjects] objectAtIndex:i];
		average += [obj average];
		y++;
	}
	
	average = average / y;
	average = (float)((int)(average * 10)) / 10.0f;
	
	return average;
}

#pragma mark --Notifications--

- (void)_updateStatus:(NSNotification *) notification
{
	[self writeFile];
}

@end
